<?php
/**
 * Add a new Proffessional Experience
 *
 * @author Xavier VILAIN
 */
use Fox\Dao\SqlFragment;
use Hive\Ressource\Wish\Localization;
use Hive\Ressource\Wish;
use Fox\Core\Errors;
use Fox\Generator;
use Hive\Ressource;
use Fox\Popup;
use Fox\Html\Screen;

$xview = Xview::instance();
$rid = $xview->val('rid');
$screen = new Screen('sWishes','add',null,true,Generator::ajaxReload('contentCol',
			Generator::url('ressource','wishes',null,array('rid' => $rid))));
$block = $xview->component('ressource','wish');
$screen->add($block)->noLegend();
if($screen->submitted()) {

	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			$label = $fields['joblist'];
			$fields['current'] = 0;

			/* @var $contact Hive\Ressource */
			$contact = Xview::instance()->component('ressource', 'object');
			$wish = new Wish();
			$fields['ressource_id'] = $rid;
			$wish->setFields($fields);
			$contact->addToWishes($wish);
			// Update Current Wish Flag
			$wish->current = 1;
			foreach($contact->wishes() as $wish) {
				$current = $wish->current;
				if($current) {
					$oldCurrentWish = $wish; 
				}
			}
			if(empty($oldCurrentWish)) {
				if(!empty($oldCurrentWish)) {
					$oldCurrentWish->current = 0;
					$contact->replaceWishes($oldCurrentWish);
				}
			}
			$contact->prepareUpdate(Ressource::CHANGE_WISH_ADD);
			$contact->update();
			// Handle Localization
			if(!empty($fields['localization'])) {
				// Find Last 
				$infos = Fox\Dao::infos(Wish::className());
				$query = $infos->handle()->createQueryBuilder();
				$query->select('MAX(did)')->from($infos->tableName(),'t');
				$fragment = new SqlFragment('ressource_id = ?',array($rid));
				$wid = $fragment->pushIn($query)->execute()->fetchColumn();
				$lastWish = new Wish($wid.':'.$rid);
				
				foreach(Localization::parseTokens($fields['localization']) as $tokenData){
					$localization = new Localization();
					$localization->setFields($tokenData);
					$lastWish->addToLocalizations($localization);
				}
				$lastWish->update();
			}
			Fox\Message::Success(Msg(\Fox\Msg::BUNDLE,\Fox\Msg::MSG_CREATE,$label));
		}
		catch (Fox\Object\Exception\Save $e){
			Fox\Message::Error($e);
		}
		catch (Fox\Object\Exception\NotExist $e)
		{
			Fox\Message::Error($e);
		}
	}
	return $xview->messages(true,true);
}
$popup = new Popup('add',Msg(Hive::BUNDLE,Hive::MSG_ADD_A_WISH),$screen,700);
return $popup->display();